package com.example.blogdemo.controller;

import com.example.blogdemo.aync.EventModel;
import com.example.blogdemo.aync.EventProducer;
import com.example.blogdemo.aync.EventType;
import com.example.blogdemo.entity.Comment;
import com.example.blogdemo.entity.HostHolder;
import com.example.blogdemo.service.ArticleService;
import com.example.blogdemo.service.CommentService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;

/**
 * @Author Anita
 * @Date 2017/12/21 17:10
 */
@Controller
public class CommentController {
    @Autowired
    private CommentService commentService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private HostHolder hostHolder;

    @RequestMapping(value = "/addComment/{articleId}",method = RequestMethod.POST)
    public String addComment(@PathVariable("articleId")int articleId,
                             @RequestParam("content")String content,Model model){
        Comment comment = new Comment();
        if(hostHolder.getUser()==null){
            return "redirect:/article/"+articleId;
        }else{
            comment.setUserId(hostHolder.getUser().getId());
        }
        comment.setContent(content);
        comment.setCreatedDate(new Date());
        comment.setArticleId(articleId);
        comment.setStatus(0);
        commentService.addComment(comment);

        int count = commentService.getCommentsCount(articleId);
        articleService.updateCommentCount(articleId,count);


//        eventProducer.fireEvent(new EventModel().setType(EventType.COMMENT)
//        .setActorId(hostHolder.getUser().getId())
//        .setExts("username",hostHolder.getUser().getName())
//        .setExts("email","test@qq.com")
//        .setExts("articleId",String.valueOf(articleId)));

        return "redirect:/article/"+articleId;
    }
}
